<template>
  <div class="blog-container">
    <!-- 热门动态区域 -->
    <div class="hot-posts">
      <el-card>
        <div class="hot-posts-header">
          <h3>热门动态</h3>
        </div>
        <div class="hot-posts-list">
          <div v-for="post in hotPosts" :key="post.id" class="hot-post-item">
            <el-avatar :size="30" :src="post.avatar === '' || post.avatar === null ? require('@/assets/default_img.jpg') : post.avatar"></el-avatar>
            <div class="hot-post-content">
              <div class="hot-post-user">{{ post.nickName }}</div>
              <div class="hot-post-text">{{ post.content }}</div>
            </div>
            <div class="hot-post-likes">
              <el-icon :size="20">
                <Star />
              </el-icon>
              {{ post.likeTotal }}
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 发布动态区域 -->
    <div class="post-area">
      <el-card>
        <el-input
          v-model="newPost.content"
          type="textarea"
          :rows="3"
          placeholder="分享新鲜事..."
        ></el-input>
        <div class="post-actions">
          <div class="preview-images" v-if="newPost.images && newPost.images.length">
            <div v-for="(img, index) in newPost.images" :key="index" class="preview-image-wrapper">
              <el-image
                :src="img"
                fit="cover"
                class="preview-image"
                style="width: 50px; height: 50px;"
              >
                <template #error>
                  <el-icon><Picture /></el-icon>
                </template>
              </el-image>
              <el-icon class="delete-icon" @click="newPost.images.splice(index, 1)">
                <Close />
              </el-icon>
            </div>
          </div>
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleImageChange"
          >
            <el-button type="primary" plain>
              <el-icon><Picture /></el-icon>
              添加图片
            </el-button>
          </el-upload>
          <el-button type="primary" @click="publishPost">发布</el-button>
        </div>
      </el-card>
    </div>

    <!-- 动态列表 -->
    <div class="posts-list">
      <el-card v-for="post in posts" :key="post.id" class="post-item">
        <!-- 用户信息 -->
        <div class="post-header">
          <el-avatar :size="40" :src="post.avatar === '' || post.avatar === null ? require('@/assets/default_img.jpg') : post.avatar"></el-avatar>
          <div class="user-info">
            <span class="username">{{ post.nickName }}</span>
            <span class="time">{{ post.createTime }}</span>
          </div>
        </div>

        <!-- 动态内容 -->
        <div class="post-content">
          <p>{{ post.content }}</p>
          <div class="post-images" v-if="post.images && post.images.length">
            <el-image 
              v-for="(img, index) in post.images"
              :key="index"
              :src="img"
              :preview-src-list="post.images"
              fit="cover"
              class="post-image"
            ></el-image>
          </div>
        </div>

        <!-- 点赞和评论区域 -->
        <div class="post-actions">
          <el-button 
            type="text" 
            @click="handleLike(post)"
            :class="{'is-liked': post.isLiked}"
          >
          <el-icon :size="20"  :color="post.isLiked ? '#409EFF' : '#909399'">
            <Star />
          </el-icon>
          <el-text style="margin-left: 0px" class="mx-1" type="primary">{{ post.likeTotal }}</el-text>
          </el-button>
          <el-button type="text" @click="showCommentInput(post)">
            <el-icon><ChatRound /></el-icon>
            评论
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-section" v-if="post.comments.length">
          <div v-for="comment in post.comments" :key="comment.id" class="comment-item">
            <span class="comment-user">{{ comment.nickName }}</span>
            <span class="comment-content">{{ comment.content }}</span>
          </div>
        </div>

        <!-- 评论输入框 -->
        <div class="comment-input" v-if="post.showCommentInput">
          <el-input
            v-model="post.newComment"
            placeholder="写下你的评论..."
            @keyup.enter="submitComment(post)"
          >
            <template #append>
              <el-button @click="submitComment(post)">发送</el-button>
            </template>
          </el-input>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  setup() {
    const newPost = reactive({
      content: '',
      images: []
    })

    onMounted(() => {
      loadingComment()
    })

    const posts = ref([
      {
        id: 1,
        nickName: '张三',
        avatar: 'https://example.com/avatar1.jpg',
        content: '今天天气真不错！',
        createTime: '2024-01-20 10:30',
        images: ['https://example.com/image1.jpg'],
        likeTotal: 12,
        isLiked: false,
        comments: [
          {
            id: 1,
            nickName: '李四',
            content: '确实很好啊！'
          }
        ],
        showCommentInput: false,
        newComment: ''
      }
    ])

    // 获取点赞最多的4条动态
    const hotPosts = computed(() => {
      return [...posts.value]
        .sort((a, b) => b.likeTotal - a.likeTotal)
        .slice(0, 4)
    })

    const loadingComment = () => {
      axios.post('/api/blog/all')
      .then(res => {
        if(res.data.code === 200) {
          posts.value = res.data.data
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error('获取动态失败')
      })
    }

    const publishPost = () => {
      const user = checkLogin()
      if(user === '') {
        return
      }
      if (!newPost.content.trim()) {
        ElMessage.warning('请输入内容')
        return
      }
      // 发布动态逻辑
      const formData = new FormData();
      formData.append('userId', user.id);
      formData.append('content', newPost.content);
      // 将图片添加到 FormData 中
      newPost.images.forEach((image, index) => {
        // 如果image是File对象直接使用,否则需要先转换成File对象
        if(image instanceof File) {
          formData.append(`images`, image);
        } else if(typeof image === 'string') {
          // 如果是Base64字符串,需要先转换成Blob再转File
          const byteString = atob(image.split(',')[1]);
          const mimeString = image.split(',')[0].split(':')[1].split(';')[0];
          const ab = new ArrayBuffer(byteString.length);
          const ia = new Uint8Array(ab);
          for(let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
          }
          const blob = new Blob([ab], {type: mimeString});
          const file = new File([blob], `image${index}.${mimeString.split('/')[1]}`, {type: mimeString});
          formData.append(`images`, file);
        }
      });

      axios.post('/api/blog/publish', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code === 200) {
          ElMessage.success('发布成功')
          newPost.content = ''
          newPost.images = []
          loadingComment()
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('发布失败')
      })
    }

    const checkLogin = () => {
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      if(user === null || user === undefined || user === '') {
        ElMessage.error('请先登录')
        return ''
      }
      return user
    }

    //处理点赞数据
    const handleLike = (post) => {
      const user = checkLogin()
      if(user === '') {
        return
      }

      axios.post('/api/blog/liked',{
        blogId: post.id,
        userId: user.id
      })
      .then(res => {
        if(res.data.code === 200) {
          const flag = res.data.data
          if(flag){
             post.isLiked = true;
             post.likeTotal += 1;
             ElMessage.success("点赞成功") 
          }else{
             post.isLiked = false;
             post.likeTotal -= 1;
             ElMessage.success("取消点赞") 
          }
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error('点赞操作失败')
      })
    }

    const showCommentInput = (post) => {
      post.showCommentInput = true
    }

    const submitComment = (post) => {
      const user = checkLogin()
      if(user === '') {
        return
      }
      if (!post.newComment.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }

      axios.put("/api/blog/comment",{
        userId: user.id,
        blogId: post.id,
        content: post.newComment
      }).then(res => {
        if(res.data.code === 200) {
          post.comments.push(res.data.data)
          post.newComment = ''
          post.showCommentInput = false
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error('评论失败')
      })
    }

    const handleImageChange = (file) => {
      const user = checkLogin()
      if(user === '') {
        return
      }
      if (file.size > 20 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过20MB')
        return false
      }
      // 直接存储File对象
      newPost.images.push(file.raw);
      return false; // 阻止自动上传
    }

    const fileUpload = (file) => {
      const formData = new FormData();
      formData.append('file', file);
      axios.post('/api/file/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          newPost.images.push(res.data.data);
          ElMessage.success('上传成功')
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error('上传失败')
      })
    }

    return {
      newPost,
      posts,
      hotPosts,
      publishPost,
      handleLike,
      showCommentInput,
      submitComment,
      fileUpload,
      handleImageChange,
      loadingComment,
      checkLogin
    }
  }
}
</script>

<style scoped>
.blog-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.hot-posts {
  margin-bottom: 20px;
}

.hot-posts-header {
  margin-bottom: 10px;
}

.hot-posts-header h3 {
  margin: 0;
  color: #303133;
}

.hot-post-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.hot-post-item:last-child {
  border-bottom: none;
}

.hot-post-content {
  flex: 1;
  margin: 0 10px;
  overflow: hidden;
}

.hot-post-user {
  font-weight: bold;
  font-size: 14px;
}

.hot-post-text {
  color: #666;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.hot-post-likes {
  color: #409EFF;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-area {
  margin-bottom: 20px;
}

.post-actions {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-item {
  margin-bottom: 20px;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  margin-left: 10px;
}

.username {
  font-weight: bold;
  margin-right: 10px;
}

.time {
  color: #999;
  font-size: 12px;
}

.post-content {
  margin: 10px 0;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5px;
  margin-top: 10px;
}

.post-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.post-actions {
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-top: 10px;
}

.is-liked {
  color: #409EFF;
}

.comments-section {
  background: #f5f5f5;
  padding: 10px;
  margin-top: 10px;
  border-radius: 4px;
}

.comment-item {
  margin: 5px 0;
}

.comment-user {
  font-weight: bold;
  margin-right: 5px;
}

.comment-input {
  margin-top: 10px;
}
</style>